package com.css.dzj.dzjdzqs.modules.supervisionrecord.service.impl;


import com.css.dzj.dzjdzqs.common.util.Constant;
import com.css.dzj.dzjdzqs.common.util.R;
import com.css.dzj.dzjdzqs.common.util.ServiceUtil;
import com.css.dzj.dzjdzqs.common.util.excel.ExcelData;
import com.css.dzj.dzjdzqs.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjdzqs.modules.supervisionrecord.entity.SupervisionEntity;
import com.css.dzj.dzjdzqs.modules.supervisionrecord.entity.QSupervisionEntity;
import com.css.dzj.dzjdzqs.modules.supervisionrecord.mapper.SupervisionMapper;
import com.css.dzj.dzjdzqs.modules.supervisionrecord.service.SupervisionService;
import com.css.dzj.dzjdzqs.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SupervisionServiceImpl implements SupervisionService {
    @Autowired
    private SupervisionMapper supervisionMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private ServiceUtil serviceUtil;

    @Autowired
    private HttpServletRequest request;

    /**
     * 新增趋势监管信息
     */

    @Override
    @Transactional
    public void add(SupervisionEntity supervisionEntity) {
        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if (r.getCode().equals("200")) {
                LoginUser userInfo = (LoginUser) r.get("data");
                if(StringUtils.isEmpty(supervisionEntity.getCreateUser())){
                    supervisionEntity.setCreateUser(userInfo.getLoginName());
                }
                if (StringUtils.isEmpty(supervisionEntity.getCreateUserUnit())){
                    supervisionEntity.setCreateUserUnit(userInfo.getOrgName());
                }
            }
            if (supervisionEntity.getCreateTime() == null){
                supervisionEntity.setCreateTime(new Date());
            }
            supervisionEntity.setDelFlag(Constant.NO_DELETE);
            supervisionEntity.setStatus("1");
            supervisionEntity.setOtherMsg("1");//保存发布
            supervisionEntity.setSubmitTime(new Date());
            supervisionMapper.save(supervisionEntity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 暂存趋势监管信息
     *
     * @param supervisionEntity
     */
    @Override
    @Transactional
    public void addOnly(SupervisionEntity supervisionEntity) {
        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if (r.getCode().equals("200")) {
                LoginUser userInfo = (LoginUser) r.get("data");
                if(StringUtils.isEmpty(supervisionEntity.getCreateUser())){
                    supervisionEntity.setCreateUser(userInfo.getLoginName());
                }
                if (StringUtils.isEmpty(supervisionEntity.getCreateUserUnit())){
                    supervisionEntity.setCreateUserUnit(userInfo.getOrgName());
                }
            }
            if (supervisionEntity.getCreateTime() == null){
                supervisionEntity.setCreateTime(new Date());
            }

            supervisionEntity.setDelFlag(Constant.NO_DELETE);
            supervisionEntity.setStatus("0");
            supervisionEntity.setOtherMsg("0");//暂存
            supervisionMapper.save(supervisionEntity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public SupervisionEntity findById(String id) {
        return supervisionMapper.getOne(id);
    }


    /**
     * 修改趋势监管信息
     */
    @Override
    @Transactional
    public void update(SupervisionEntity supervisionEntity) {

    }

    /**
     * 删除趋势监管信息
     */
    @Override
    @Transactional
    public Boolean delete(String id) {

        QSupervisionEntity qSupervisionEntity = QSupervisionEntity.supervisionEntity;
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("参数为空");
        }
        try {
            jpaQueryFactory
                    .update(qSupervisionEntity)
                    .set(qSupervisionEntity.delFlag, Constant.DELETE)
                    .where(
                            qSupervisionEntity.id.eq(id),
                            qSupervisionEntity.delFlag.eq(Constant.NO_DELETE)
                    )
                    .execute();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 多条件分页查询趋势监管信息
     */
    @Override
    public QueryResults<SupervisionEntity> getSupervisionList(String createUser, String title, String supervisionObjectName, String createUserUnit, String status, String releaseStartTime, String releaseEndTime, Pageable pageable) {

        QSupervisionEntity qSupervisionEntity = QSupervisionEntity.supervisionEntity;

        Predicate predicate = qSupervisionEntity.isNotNull().or(qSupervisionEntity.isNull());
        predicate = ("".equals(createUser) || createUser == null) ? predicate : ExpressionUtils.and(predicate, qSupervisionEntity.createUser.like("%" + createUser + "%"));
        predicate = ("".equals(title) || title == null) ? predicate : ExpressionUtils.and(predicate, qSupervisionEntity.title.like("%" + title + "%"));
        predicate = ("".equals(supervisionObjectName) || supervisionObjectName == null) ? predicate : ExpressionUtils.and(predicate, qSupervisionEntity.supervisionObjectName.like("%" + supervisionObjectName + "%"));
        predicate = ("".equals(createUserUnit) || createUserUnit == null) ? predicate : ExpressionUtils.and(predicate, qSupervisionEntity.createUserUnit.like("%" + createUserUnit + "%"));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, qSupervisionEntity.status.eq(status));

        /** 开始时间为空，结束时间不为空  updated by liyuan **/
        if ((StringUtils.isEmpty(releaseStartTime)) && (!StringUtils.isEmpty(releaseEndTime))) {
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(releaseEndTime+ " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, qSupervisionEntity.createTime.loe(endDate));
        }
        /** 开始时间不为空，结束时间为空  updated by liyuan **/
        if ((!StringUtils.isEmpty(releaseStartTime)) && (StringUtils.isEmpty(releaseEndTime))) {
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, qSupervisionEntity.createTime.goe(startDate));
        }
        /** 开始时间不为空，结束时间为空  **/
        if ((!StringUtils.isEmpty(releaseStartTime)) && (!StringUtils.isEmpty(releaseEndTime))) {
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime+" "+"00:00:00.000");
                endDate = sf.parse(releaseEndTime+ " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, qSupervisionEntity.createTime.between(startDate, endDate));
        }

        predicate = ExpressionUtils.and(predicate, qSupervisionEntity.delFlag.eq(Constant.NO_DELETE));

        return jpaQueryFactory
                .selectFrom(qSupervisionEntity)
                .where(
                        predicate
                )
                .orderBy(qSupervisionEntity.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    @SneakyThrows
    @Override
    public void exportDetailToExcel(HttpServletResponse response, List<SupervisionEntity> supervisionEntityList) {
        /*if (supervisionEntityList == null || supervisionEntityList.size() <= 0) {
            throw new RuntimeException("数据为空！");
        }*/
        //导出实体
        ExcelData data = new ExcelData();
        data.setName("擅自公告监测记录信息表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("标题");
        titles.add("创建者");
        titles.add("创建者单位");
        titles.add("状态");
        titles.add("创建时间");
        titles.add("监测名称");
        titles.add("监测内容");
        titles.add("提交时间");
        titles.add("其它信息");
        titles.add("其他提示");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (SupervisionEntity supervision : supervisionEntityList) {
            ArrayList<Object> row = new ArrayList<>();
            row.add(supervision.getTitle());
            row.add(supervision.getCreateUser());
            row.add(supervision.getCreateUserUnit());
            row.add(supervision.getStatus());
            row.add(supervision.getCreateTime());
            row.add(supervision.getSupervisionObjectName());
            row.add(supervision.getSupervisionRecordContent());
            row.add(supervision.getSubmitTime());
            row.add(supervision.getOtherMsg());
            row.add(supervision.getOtherTip());
            rows.add(row);
        }
        data.setRows(rows);
        // 导出
        ExportExcelUtils.exportExcel(response, "擅自公告监测记录信息表.xlsx", data);
    }

    @Transactional
    @Override
    public void submit(String id) {
        QSupervisionEntity q = QSupervisionEntity.supervisionEntity;
        jpaQueryFactory.update(q).set(q.status, "1").set(q.submitTime, new Date())
                .where(q.id.eq(id), q.delFlag.eq(Constant.NO_DELETE))
                .execute();
    }


}
